﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using LevenBlog.Core.Utils;

namespace LevenBlog.Core.Install.Operations {
    public class FileSystemCheck : IInstallOperation {
        #region IInstallOperation Members

        public string Name {
            get { return CoreResource.install_filesystemcheck_name; }
        }

        public string Intro {
            get { return CoreResource.install_filesystemcheck_intro; }
        }

        public object Data {
            get;
            set;
        }

        public OperationResult Execute(OperationContext context) {
            List<string> errors = new List<string>();
            string folder = Convert.ToString(Data).Replace('\\', '/');
            string path = folder;
            try {
                string realPath = HttpContext.Current.Server.MapPath(path);
                if (Directory.Exists(realPath)) {
                    if (!realPath.EndsWith("\\"))
                        realPath += "\\";
                    realPath += "test.txt";
                    using (File.Create(realPath)) { };
                    File.Delete(realPath);
                } else {
                    using (FileStream fs = new FileStream(realPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) {
                        if (!fs.CanWrite) {
                            throw new Exception("error write.");
                        }
                    }
                }
                
            } catch {
                errors.Add(String.Format(CoreResource.install_filesystemcheck_error, folder));
            }
            return new OperationResult(errors.Count > 0 ? false : true, errors);
        }

        #endregion
    }
}
